package me.hys.service.doctor.impl;

import java.util.Map;

import me.hys.base.ApiResult;
import me.hys.cons.ApiStatus;
import me.hys.cons.UserType;
import me.hys.dao.doctor.IPatientMapper;
import me.hys.dao.system.IUserMapper;
import me.hys.entity.doctor.PatientEntity;
import me.hys.entity.system.UserEntity;
import me.hys.kits.StrKit;
import me.hys.service.doctor.IPatientManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;

/**
 * Author: @author HYS . <br>
 * Date: 2015-11-23 下午9:19:24 . <br>
 * Function:
 */
@Service
@Transactional
class PatientManagerImpl implements IPatientManager {
	@Autowired
	private IPatientMapper patientMapper;
	@Autowired
	private IUserMapper userMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.doctor.IPatientManager#findById(java.lang.String)
	 */
	@Override
	public PatientEntity findById(String userid) {
		return patientMapper.findById(userid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.doctor.IPatientManager#getCaseImageCount(java.lang.String)
	 */
	@Override
	public int getCaseImageCount(String userid) {
		String count = patientMapper.getCaseImageCount(userid);
		return StrKit.isBlank(count) ? 0 : Integer.parseInt(count);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.doctor.IPatientManager#saveCaseImageCount(java.lang.String
	 * , int)
	 */
	@Override
	public ApiResult saveCaseImageCount(String userid, int caseImageCount) {
		Map<String, Object> params = Maps.newHashMap();
		params.put("userid", userid);
		params.put("caseImageCount", caseImageCount);
		int result = patientMapper.updateCaseImageCount(params);
		if (result == 0) {
			PatientEntity entity = new PatientEntity();
			entity.setUserid(Integer.parseInt(userid));
			entity.setCaseImageCount(caseImageCount);
			patientMapper.saveCaseImageCount(entity);
			result = 1;
		}
		return new ApiResult(result, "操作成功");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.doctor.IPatientManager#saveOrUpdate(me.hys.entity.doctor
	 * .PatientEntity)
	 */
	@Override
	public ApiResult saveOrUpdate(PatientEntity entity) {
		ApiResult apiResult = new ApiResult(ApiStatus.FAILED);
		UserEntity user = userMapper.findById(entity.getUserid() + "");
		if (null == user) {
			apiResult.setMsg("该用户不存在");
			return apiResult;
		}
		if (user.getType() != UserType.PATIENT.getType()) {
			apiResult.setMsg("非患者用户无法更新");
			return apiResult;
		}
		// 如果更新影响为0
		if (patientMapper.update(entity) == 0) {
			// 那么就在患者表中插入一条记录
			patientMapper.save(entity);
		}
		apiResult.setResult(ApiStatus.SUCCESS);
		apiResult.setMsg("更新信息成功");
		return apiResult;
	}
}
